package cn.cai.pethome.base.util;


import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SmsUtil {

    @Value("${sms.uid}")
    private String uid;
    @Value("${sms.key}")
    private String key;



    /**
     * 发送短信
     * @param phone 接收短信的手机号，多个手机号以逗号隔开
     * @param text 短信内容
     */
    public void sendSms(String phone, String text) {
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("https://utf8api.smschinese.cn/");
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
            //键值对  请求参数
            NameValuePair[] data = {
                    new NameValuePair("Uid", uid),
                    new NameValuePair("Key", key),
                    new NameValuePair("smsMob",phone),
                    new NameValuePair("smsText",text)
            };
            post.setRequestBody(data);   //设置请求体json

            client.executeMethod(post); //执行发送请求
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode); //HTTP状态码
            for(Header h : headers){
                System.out.println(h.toString());
            }
            //得到响应结果
            String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
            System.out.println(result);  //打印返回消息状态

            post.releaseConnection();   //释放连接
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}